// 导入vue类
import Vue from 'vue'
// 导入路由类
import VueRouter from "vue-router"
// 导入登录组件
import Login from "../components/Login.vue"
import Home from "../components/Home.vue"
import Welcome from "../components/Welcome.vue"
import User from "../components/User/User.vue"
import Rights from "../components/Power/Rights.vue"
import Roles from "../components/Power/Roles.vue"
import Cate from "../components/goods/Cate.vue"
import Params from "../components/goods/Params.vue"

// 全局注册路由组件标签 路由组件/标签 <router-view></router-view>
Vue.use(VueRouter)
// 创建 路由规则
const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/Welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: User
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      },
      {
        path: "/categories",
        component: Cate
      },
      {
        path: "/params",
        component: Params
      }

    ]
  }
]
// 创建并导出路由管理器 对象
const router = new VueRouter({ routes })
// 添加路由守卫
// 挂载路由导航守卫,to表示将要访问的路径，from表示从哪里来，next是下一个要做的操作
router.beforeEach((to, from, next) => {
  // 如果访问/login 直接放行
  if (to.path === '/login') return next();
  // 如果 不是访问/login 则检查sessionStorage中是否有token
  const tokenStr = window.sessionStorage.getItem('token');
  if (!tokenStr) return next('/login');
  // 如果访问非/login 并且有token则放行
  next(true);

})

// 导出 路由管理器 对象
export default router